package com.zhunaer.dao.impl;

import com.zhunaer.dao.ShopDao;
import com.zhunaer.entity.Shop;
import com.zhunaer.utils.JDBCUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 店铺数据访问对象实现类
 * 提供对店铺表的CRUD操作实现
 */
public class ShopDaoImpl implements ShopDao {

    /**
     * 插入新店铺记录
     * @param shop 店铺实体对象
     * @return 插入成功返回生成的主键ID，失败返回-1
     */
    @Override
    public int insert(Shop shop) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            // 获取数据库连接
            conn = JDBCUtils.getConnection();
            // 准备SQL语句，设置RETURN_GENERATED_KEYS以获取生成的主键
            String sql = "INSERT INTO shops(user_id, shop_name, address, contact, keywords, apply_status) VALUES(?,?,?,?,?,?)";
            pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

            // 设置参数
            pstmt.setInt(1, shop.getUserId());
            pstmt.setString(2, shop.getShopName());
            pstmt.setString(3, shop.getAddress());
            pstmt.setString(4, shop.getContactInfo());
            pstmt.setString(5, shop.getKeywords());
            pstmt.setInt(6, shop.getApplyStatus());

            // 执行插入操作
            int affectedRows = pstmt.executeUpdate();

            // 如果插入成功，获取生成的主键
            if (affectedRows > 0) {
                rs = pstmt.getGeneratedKeys();
                if (rs.next()) {
                    return rs.getInt(1);
                }
            }
            return -1;
        } catch (SQLException e) {
            throw new RuntimeException("创建店铺失败", e);
        } finally {
            // 释放资源
            JDBCUtils.close(conn, pstmt, rs);
        }
    }

    /**
     * 更新店铺信息
     * @param shop 店铺实体对象
     * @return 受影响的行数
     */
    @Override
    public int update(Shop shop) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils.getConnection();
            // 准备更新SQL语句
            String sql = "UPDATE shops SET shop_name=?, address=?, contact=?, keywords=?, apply_status=? WHERE shop_id=?";
            pstmt = conn.prepareStatement(sql);

            // 设置参数
            pstmt.setString(1, shop.getShopName());
            pstmt.setString(2, shop.getAddress());
            pstmt.setString(3, shop.getContactInfo());
            pstmt.setString(4, shop.getKeywords());
            pstmt.setInt(5, shop.getApplyStatus());
            pstmt.setInt(6, shop.getShopId());

            // 执行更新操作
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("更新店铺失败", e);
        } finally {
            JDBCUtils.close(conn, pstmt, null);
        }
    }

    /**
     * 根据ID查询店铺
     * @param shopId 店铺ID
     * @return 店铺实体对象，未找到返回null
     */
    @Override
    public Shop findById(Integer shopId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            // 准备查询SQL，限制返回1条记录
            String sql = "SELECT * FROM shops WHERE shop_id=? LIMIT 1";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, shopId);
            rs = pstmt.executeQuery();

            // 如果查询到结果，映射为Shop对象
            if (rs.next()) {
                return mapRowToShop(rs);
            }
            return null;
        } catch (SQLException e) {
            throw new RuntimeException("根据ID查询店铺失败", e);
        } finally {
            JDBCUtils.close(conn, pstmt, rs);
        }
    }

    /**
     * 根据用户ID查询店铺列表
     * @param userId 用户ID
     * @return 店铺列表，无结果返回空列表
     */
    @Override
    public List<Shop> findByUserId(Integer userId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Shop> shops = new ArrayList<>();
        try {
            conn = JDBCUtils.getConnection();
            // 准备根据用户ID查询的SQL
            String sql = "SELECT * FROM shops WHERE user_id=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            rs = pstmt.executeQuery();

            // 遍历结果集，映射为Shop对象并添加到列表
            while (rs.next()) {
                shops.add(mapRowToShop(rs));
            }
            return shops;
        } catch (SQLException e) {
            throw new RuntimeException("根据用户ID查询店铺失败", e);
        } finally {
            JDBCUtils.close(conn, pstmt, rs);
        }
    }

    /**
     * 查询所有店铺
     * @return 所有店铺列表，无结果返回空列表
     */
    @Override
    public List<Shop> findAll() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Shop> shops = new ArrayList<>();
        try {
            conn = JDBCUtils.getConnection();
            // 准备查询所有店铺的SQL
            String sql = "SELECT * FROM shops";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            // 遍历结果集，映射为Shop对象
            while (rs.next()) {
                shops.add(mapRowToShop(rs));
            }
            return shops;
        } catch (SQLException e) {
            throw new RuntimeException("查询所有店铺失败", e);
        } finally {
            JDBCUtils.close(conn, pstmt, rs);
        }
    }

    /**
     * 根据条件查询店铺
     * @param keyword 搜索关键词，匹配店铺名称或关键词
     * @param status 申请状态
     * @return 符合条件的店铺列表，无结果返回空列表
     */
    @Override
    public List<Shop> findByCondition(String keyword, String status) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Shop> shops = new ArrayList<>();
        try {
            conn = JDBCUtils.getConnection();
            // 动态构建SQL语句
            StringBuilder sql = new StringBuilder("SELECT * FROM shops WHERE 1=1");

            // 根据参数添加查询条件
            if (keyword != null && !keyword.isEmpty()) {
                sql.append(" AND (shop_name LIKE ? OR keywords LIKE ?)");
            }
            if (status != null && !status.isEmpty()) {
                sql.append(" AND apply_status = ?");
            }

            pstmt = conn.prepareStatement(sql.toString());
            int paramIndex = 1;

            // 设置查询参数
            if (keyword != null && !keyword.isEmpty()) {
                String likeKeyword = "%" + keyword + "%";
                pstmt.setString(paramIndex++, likeKeyword);
                pstmt.setString(paramIndex++, likeKeyword);
            }
            if (status != null && !status.isEmpty()) {
                pstmt.setString(paramIndex++, status);
            }

            // 执行查询并处理结果集
            rs = pstmt.executeQuery();
            while (rs.next()) {
                shops.add(mapRowToShop(rs));
            }
            return shops;
        } catch (SQLException e) {
            throw new RuntimeException("条件查询店铺失败", e);
        } finally {
            JDBCUtils.close(conn, pstmt, rs);
        }
    }

    /**
     * 更新店铺审核状态
     * @param shopId 店铺ID
     * @param auditStatus 审核状态
     * @return 受影响的行数
     */
    @Override
    public int updateAuditStatus(Integer shopId, Integer auditStatus) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils.getConnection();
            // 准备更新审核状态的SQL
            String sql = "UPDATE shops SET audit_status=? WHERE shop_id=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, auditStatus);
            pstmt.setInt(2, shopId);
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("更新审核状态失败", e);
        } finally {
            JDBCUtils.close(conn, pstmt, null);
        }
    }

    /**
     * 更新店铺营业状态
     * @param shopId 店铺ID
     * @param businessStatus 营业状态
     * @return 受影响的行数
     */
    @Override
    public int updateBusinessStatus(Integer shopId, Integer businessStatus) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils.getConnection();
            // 准备更新营业状态的SQL
            String sql = "UPDATE shops SET business_status=? WHERE shop_id=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, businessStatus);
            pstmt.setInt(2, shopId);
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("更新营业状态失败", e);
        } finally {
            JDBCUtils.close(conn, pstmt, null);
        }
    }

    /**
     * 将ResultSet中的一行数据映射为Shop对象
     * @param rs 结果集对象
     * @return 映射后的Shop对象
     * @throws SQLException 数据库异常
     */
    private Shop mapRowToShop(ResultSet rs) throws SQLException {
        Shop shop = new Shop();
        shop.setShopId(rs.getInt("shop_id"));
        shop.setUserId(rs.getInt("user_id"));
        shop.setShopName(rs.getString("shop_name"));
        shop.setAddress(rs.getString("address"));
        shop.setContactInfo(rs.getString("contact"));
        shop.setKeywords(rs.getString("keywords"));
        shop.setBusinessStatus(rs.getInt("business_status"));
        shop.setAuditStatus(rs.getInt("audit_status"));
        shop.setCreateTime(new Date(rs.getTimestamp("create_time").getTime()));
        return shop;
    }
}